package com.xiaowanzi.transporter.handler;

import com.xiaowanzi.transporter.handler.resolver.MessageResolverFactory;
import com.xiaowanzi.transporter.handler.resolver.PingMessageResolver;
import com.xiaowanzi.transporter.handler.resolver.PongMessageResolver;
import com.xiaowanzi.transporter.handler.resolver.RequestMessageResolver;
import com.xiaowanzi.transporter.handler.resolver.Resolver;
import com.xiaowanzi.transporter.handler.resolver.ResponseMessageResolver;
import com.xiaowanzi.transporter.model.Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ServerMessageHandler extends SimpleChannelInboundHandler<Message> {

  private MessageResolverFactory resolverFactory = MessageResolverFactory.getInstance();

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, Message message) throws Exception {
    Resolver resolver = resolverFactory.getMessageResolver(message);
    Message result = resolver.resolve(message);
    ctx.writeAndFlush(result);
  }

  @Override
  public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    resolverFactory.registerResolver(new RequestMessageResolver());
    resolverFactory.registerResolver(new ResponseMessageResolver());
    resolverFactory.registerResolver(new PingMessageResolver());
    resolverFactory.registerResolver(new PongMessageResolver());
  }
}
